//
//  BiImagePool.m
//  CodoonBikeApp
//
//  Created by ChenBin on 14-3-26.
//  Copyright (c) 2014年 Nahan Cop. All rights reserved.
//

#import "BiImagePool.h"
#import "BiFileManager.h"

@interface BiImagePool(PRIVATE)
- (UIImage *)imageWithFileName:(NSString*)fileName;
@end

@implementation BiImagePool

SINGLE_INSTANCE_IMPLEMENTION(BiImagePool)

- (id)init
{
    if (self = [super init])
    {
        _imageCache = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

- (void)clearImageCache
{
    [_imageCache removeAllObjects];
}

- (UIImage *)loadImageWithCache:(NSString*)fileName
{
    if (nil == fileName)
    {
        return nil;
    }
    
    UIImage * image = [_imageCache objectForKey:fileName];
    
    if (nil == image)
    {
        image = [self imageWithFileName:fileName];
        
        if (nil != image)
        {
            [_imageCache setObject:image forKey:fileName];
        }
    }
    
    return image;
}

- (UIImage *)loadImageWithoutCache:(NSString*)fileName
{
    if (nil == fileName)
    {
        return nil;
    }
    
    return [self imageWithFileName:fileName];
}

- (UIImage *)imageWithFileName:(NSString*)fileName
{
    NSString * rootPath = [[NSBundle mainBundle] resourcePath];
    NSString * imagePath = [NSString stringWithFormat:@"%@/resource/%@", rootPath, fileName];
    
    return [UIImage imageWithContentsOfFile:imagePath];
}

/**
 *  加载下载的图片
 */
- (UIImage*)loadDownloadImageWithCache:(NSString*)fileName
{
    if (nil == fileName)
    {
        return nil;
    }
    
    UIImage * image = [_imageCache objectForKey:fileName];
    
    if (nil == image)
    {
        image = [self imageWithDownloadFileName:fileName];
        
        if (nil != image)
        {
            [_imageCache setObject:image forKey:fileName];
        }
    }
    
    return image;
}
- (UIImage*)imageWithDownloadFileName:(NSString*)fileName
{
    NSString * imagePath = [NSString stringWithFormat:@"%@/%@", [BiFileManager imageRootPath], fileName];
    
    return [UIImage imageWithContentsOfFile:imagePath];
}

@end
